---@module 用户的orm数据结构

local _acu = class("ActivityUsr", require("framework.orm.base"))
--======================================
--default params
local d = Ding
local Logger = d.Logger
local uuid = d.uuid
--======================================

local TOKEN_EXPIRE_TIME = 60 * 60 * 4 --4 hours  token
local REFRESH_TOKEN_EXPIRE_TIME = 60 * 60 * 24 * 2--2 days  refresh_token

--错误描述
local ERR_DESC = {
    create_failed = {errcode = 101, errdesc = "create user failed"}
}
local ACCESS_TOKEN_KEYNAME = "ACCESS_TOKEN:"
local REFRESH_TOKEN_KEYNAME = "REFRESH_TOKEN:"

local function new_accesstoken()
    return uuid()
end 

local function new_refreshtoken()
    return uuid()
end

function _acu:ctor(cacheinc)
    self.super.ctor(self, cacheinc)
end

function _acu:new_model(...)
    local exparams = {...}
    local emp_acu = {
        access_token = new_accesstoken(), 
        refresh_token = new_refreshtoken(),
        expires_in = ngx.now() + TOKEN_EXPIRE_TIME,
        token_type = "bearer",
        scope = exparams[2] or "user_info",
        authtype = "heyzf"
    }
    return emp_acu
end

function _acu:refresh_token(gid, refreshtoken)
    local ref_key = REFRESH_TOKEN_KEYNAME..(gid)
    local is_ref =  self:_dc():find_one(ref_key)
    if not is_ref then return false end 
    local ref_token = new_refreshtoken()
    local expire_in = ngx.time() + TOKEN_EXPIRE_TIME
    local issuc = self:_dc():insert_data(ref_key, ref_token)
    local issuc_1, cmd = self:_dc():expire(ref_key, expire_in)
    return (issuc and issuc_1), ref_token, expire_in
end

function _acu:cache_tokens(...) --gid, scope
    if not self:_dc() then return end 
    local data = self:new_model(...)
    self._model = data
    local params = {...}
    local gid = params[1]
    local acc_key =  ACCESS_TOKEN_KEYNAME..(gid)
    local ref_key =  REFRESH_TOKEN_KEYNAME..(gid)
    local is_suc1 = self:_dc():insert_data(acc_key, data["access_token"])
    local is_suc1_1

    local is_suc2 = self:_dc():insert_data(ref_key, data["refresh_token"])
    local is_suc2_1

    is_suc1_1 = self:_dc():expire(acc_key, ngx.time() + TOKEN_EXPIRE_TIME)
    is_suc2_1 = self:_dc():expire(ref_key, ngx.time() + REFRESH_TOKEN_EXPIRE_TIME)

    return (is_suc1 and is_suc1_1) and (is_suc1_1 and is_suc2_1)
end

--[[ ======================复写父类函数======================== ]]
function _acu:find(lconf)
    local gid = lconf["gid"]
    if not gid then return false end 
    Logger:debug("--->>[orm modelusr]find:%s", ACCESS_TOKEN_KEYNAME..(gid))
    return self:find_all_with_tbname(ACCESS_TOKEN_KEYNAME..(gid))
end
--[[ ======================复写父类函数======================== ]]


return _acu
